<!-- 也可以使用第三方库：sorttable -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .list {
        display: flex;
        flex-direction: column;
        align-items: center;
      }
      .list-item {
        width: 500px;

        height: 50px;
        background-color: rgb(123, 222, 188);
        color: #fff;
        line-height: 50px;
        margin-top: 10px;
        border-radius: 10px;
        padding-left: 10px;
        font-size: 16px;
        cursor: move;
        user-select: none;
      }
      .list-item.moving {
        background-color: transparent;
        color: transparent;
        /* border: 1px dashed #ccc; */
        background-color: rgb(48, 184, 136);
        color: #fff;
      }
    </style>
  </head>
  <body>
    <div class="list">
      <div draggable="true" class="list-item">1</div>
      <div draggable="true" class="list-item">2</div>
      <div draggable="true" class="list-item">3</div>
      <div draggable="true" class="list-item">4</div>
      <div draggable="true" class="list-item">5</div>
    </div>
    <script>
      const list = document.querySelector(".list");
      // 当前拖动的元素
      let sourceNode;
      // 事件委托
      list.ondragstart = (e) => {
        // 延迟更改样式，不然正在拖动的样式也没有
        setTimeout(() => {
          e.target.classList.add("moving");
        }, 0);
        sourceNode = e.target;
        e.dataTransfer.effectAllowed = "move";
      };
      // 阻止默认事件
      list.ondragover = (e) => {
        e.preventDefault();
      };
      list.ondragenter = (e) => {
        e.preventDefault();
        if (e.target === list || e.target === sourceNode) {
          return;
        }
        // 获取所有的元素，整理成数组
        const childrens = Array.from(list.children);
        // 正在拖动的下标
        const sourceIndex = childrens.indexOf(sourceNode);
        // 拖动进入的下标
        const targetIndex = childrens.indexOf(e.target);
        if (sourceIndex < targetIndex) {
          list.insertBefore(sourceNode, e.target.nextElementSibling);
          // console.log("向下拖动");
        } else {
          list.insertBefore(sourceNode, e.target);
          // console.log("向上拖动");
        }
      };
      list.ondragend = (e) => {
        e.target.classList.remove("moving");
      };
    </script>
  </body>
</html>
